const db = require('../db/index')
const sequelize = require('sequelize')
const { Op } = require("sequelize")
//引入用户模型
const initModels = require('../models/init-models')
const Org = initModels(db).info_orgs
const Inspiration = initModels(db).inspiration_count
const Type = initModels(db).type_count
const Person = initModels(db).info_person

//获取机构信息的函数
 exports.getOrgInfo = async (req,res) => {
     try{
         await db.sync()
         let result = await Org.findAll({
             order: [
                 ['personCount',req.query.order]
             ]
         })
         res.send({
             status: 0,
             message: '获取机构信息成功',
             data: result
         })
     } catch (error) {
         res.cc(error)
     }
 }
 //人物类型分布
exports.getDistribution = async (req,res) => {
    try{
        const { orgId } =req.body
        await db.sync()
        let result = await Type.findAll({
            attributes: [['id','code'],['type','name'],['count','value']],
            where: {
                orgId
            }
        })
        res.send({
            status: 0,
            message: '获取人物类型分布成功',
            data: result
        })
    } catch (error) {
        res.cc(error)
    }
}
//灵感排名
exports.getInspirationRank = async (req,res) =>{
    try{
        const params =req.body
        await db.sync()
        const where = {};
        Object.keys(params).forEach(key => {
            if (params[key] !== undefined && params[key] !== null && params[key] !== '') {
                where[key] = params[key];
            }
        })
        let result = await Inspiration.findAll({
            attributes: [['inspiration','code'],['inspiration','name'],[sequelize.fn('SUM',sequelize.col('count')),'value']],
            where,
            group: 'inspiration',
            order: [
                [sequelize.literal('value'),'ASC']
            ]
        })
        res.send({
            status: 0,
            message: '获取灵感排名成功',
            data: result
        })
    } catch (error) {
        res.cc(error)
    }
}
//人物信息
exports.personInfo = async (req,res) => {
    try{
        await db.sync()
        const { nameStr,page,limit,orderRow,order } = req.body
        const where = {};
        if(nameStr !== undefined && nameStr !== null && nameStr !==''){
            where[Op.or] = [
                { name: {[Op.like]: nameStr} },
                { enName: {[Op.like]: nameStr} }
            ]
        }
        let { count, rows } = await Person.findAndCountAll({
            where,
            offset: (page - 1)*limit,
            limit: limit*1,
            order: [[orderRow,order]]
        })
        res.pageSend('查询成功！',0,rows,count,limit,page)
    } catch (error) {
        res.cc(error)
    }
}
